package dxn.nl.file.client.model.serialize;

import dxn.nl.file.client.model.serialize.api.ObjectInputStream;
import dxn.nl.file.client.model.serialize.api.ObjectOutputStream;
import dxn.nl.file.client.model.serialize.api.Serialization;
import dxn.nl.file.client.model.serialize.protostuff.ProtostuffSerialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class SerializerDispatcher {

    public byte[] serialize(Object obj) throws Exception {
        Serialization serialization = new ProtostuffSerialization(); //SerializeFactory.getSerialization(serializationType);
        try (ByteArrayOutputStream byteBufOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = serialization.serialize(byteBufOutputStream)) {
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            return byteBufOutputStream.toByteArray();
        }
    }

    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        Serialization serialization = new ProtostuffSerialization();//SerializeFactory.getSerialization(serializationType);
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
             ObjectInputStream objectInputStream = serialization.deserialize(byteArrayInputStream)) {
            return objectInputStream.readObject(clazz);
        }
    }
}
